package com.loong.musicdemo;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Pair;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.palette.graphics.Palette;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.loong.musicdemo.adapter.LrcAdapter;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.service.AutoPlayService;
import com.loong.musicdemo.ui.playsong.SongListPagerAdapter;
import com.loong.musicdemo.util.BlurUtil;
import com.loong.musicdemo.util.FormatTimeUtil;
import com.loong.musicdemo.util.MergeImage;
import com.loong.musicdemo.util.dataDeal.LrcDeal;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.loong.musicdemo.util.enumutil.PlaySongType;
import com.loong.musicdemo.widget.layoutmanager.CenterLayoutManager;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static org.litepal.LitePalApplication.getContext;

/**
 * 歌曲播放活动
 */
public class PlaySongActivity extends AppCompatActivity implements View.OnClickListener {
    protected static final int VOLUME_CHANGED = 0x0922;//1.声音控制id号

    private static Bitmap albumBitmap;//1.黑圈专辑图片

    private static ObjectAnimator animator;
    private static Song currentSong = new Song();//当前歌曲
    private static String songId;
    private static List<Pair<Long, String>> lrc = new ArrayList<>();
    private static PlaySongType playSongType = PlaySongType.SEQUENTIAL;//当前播放类型,出师未顺序播放

    private static int currentItem;//当前歌词项
    private AudioManager audioManager;//媒体控制器


    @SuppressLint("StaticFieldLeak")
    private static RelativeLayout showLrcTwo;//有歌词需要显示的
    @SuppressLint("StaticFieldLeak")
    private static TextView noLrc;//无歌词需要显示的
    /*封面图片与背景*/
    private static CircleImageView ivMusic;//封面图片
    private static CoordinatorLayout bcgImg;//背景
    private static LrcAdapter adapter;//1.歌词适配器
    private static RecyclerView recyclerViewLrc;//1.歌词显示列表
    private static CenterLayoutManager centerLayoutManager;//1.自定义歌词显示布局

    /*歌词相关*/
    //1.歌曲进度条 2.声音调节
    @SuppressLint("StaticFieldLeak")
    private static SeekBar seekBar, volumeAdjustment;
    //1.显示歌词页 2.显示封面与动画 3.选择时间的线性布局
    private LinearLayout showLrc;
    private RelativeLayout showImgAnimation;
    //1.对应播放方式按钮 2.播放上一首 3.播放暂停\开始\继续 4.播放下一首 5.播放列表信息 6.点击更改进度小按钮 7.关闭音乐音量
    @SuppressLint("StaticFieldLeak")
    private static ImageButton playTypeIB, playLastIB, playControlIB, playNextIB, playListIB, selectLrcDuration, volumeControl;
    //1.当前时间文本 2.总时间文本 3.选中项歌词对应时间
    @SuppressLint("StaticFieldLeak")
    private static TextView currentTimeTV, totalTimeTV, selectTime;
    private ViewPager viewPager;


    //播放服务相关
    Intent intent;
    private static AutoPlayService.MusicControl control;//控制服务
    MusicPlayConn conn;
    private static PlayStatus playStatus = PlayStatus.INIT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //背景图片融合
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        setContentView(R.layout.activity_play_song);

        //设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        //获取数据
        Intent intent = getIntent();
        songId = intent.getStringExtra("songId");
        Message msg = AutoPlayService.handler.obtainMessage();//创建消息对象
        //讲传来的音乐id封装至消息对象中
        Bundle bundle = new Bundle();
        bundle.putString("songId", songId);
        msg.setData(bundle);
        AutoPlayService.handler.sendMessage(msg);
        initView();
        initEvent();
        initLrcRecyclerView();//初始化歌词列表设置
        initSongListPages();//初始化viewpaper

        new GetLrcTask().execute();
        //开启音量监听进程
        new Thread(new VolumeThread()).start();
        //加载歌曲封面等信息
        new GetSongDetailTask().execute();
    }

    /**
     * 初始化播放列表的ViewPager
     */
    private void initSongListPages() {
        SongListPagerAdapter pagerAdapter = new SongListPagerAdapter(this, getSupportFragmentManager());
        viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setPageMargin(30);  // setPageMargin表示设置page之间的间距
    }

    /**
     * 初始化歌词列表设置
     */
    private void initLrcRecyclerView() {
        //初始化适配器等
        centerLayoutManager = new CenterLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerViewLrc.setLayoutManager(centerLayoutManager);//使用自定义视图管理器.可实现定位中间子项
        adapter = new LrcAdapter(lrc);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recyclerViewLrc);
        recyclerViewLrc.setAdapter(adapter);
        //设置歌词的点击事件
        adapter.setOnPlayClickListener(() -> {
            showLrc.setVisibility(View.GONE);
            showImgAnimation.setVisibility(View.VISIBLE);
        });
    }

    /**
     * 初始化视图
     */
    private void initView() {
        /*歌曲封面图片整合*/
        showImgAnimation = findViewById(R.id.show_img_animation);//封面页
        /*封面页控件*/
        bcgImg = findViewById(R.id.bcgImg);
        ivMusic = findViewById(R.id.iv_music);
        animator = ObjectAnimator.ofFloat(ivMusic, "rotation", 0f, 360.0f);
        animator.setDuration(10000);  //动画旋转一周的时间为10秒
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);  //-1表示设置动画无限循环
        albumBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.play_song_album_bg);//获取封面的黑胶图片

        /*歌词页控件*/
        showLrc = findViewById(R.id.show_lrc);//歌词页
        showLrcTwo = findViewById(R.id.show_lrc_two);//有歌词显示
        noLrc = findViewById(R.id.no_lrc);//无歌词显示
        selectLrcDuration = findViewById(R.id.trans_duration_click);//选择进度
        selectTime = findViewById(R.id.current_time);//选中项时间
        recyclerViewLrc = findViewById(R.id.recycler_lrc);//歌词显示

        /*音量控制相关*/
        volumeAdjustment = findViewById(R.id.volume_adjustment);//声音调节进度条
        volumeControl = findViewById(R.id.volume_control);//声音控制按钮
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);//获取媒体服务
        //初始化音量
        //最大音量
        int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获取音乐的最大音量
        volumeAdjustment.setMax(streamMaxVolume);
        //当前音量
        int streamCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获取当前音量
        volumeAdjustment.setProgress(streamCurrentVolume);
        /*底部控制栏*/
        seekBar = findViewById(R.id.sb);//进度条
        playTypeIB = findViewById(R.id.play_type_image_button);
        playLastIB = findViewById(R.id.play_last_image_button);
        playControlIB = findViewById(R.id.play_controller_image_button);
        playNextIB = findViewById(R.id.play_next_image_button);
        playListIB = findViewById(R.id.play_list_image_button);
        currentTimeTV = findViewById(R.id.tv_progress);//当前时间
        totalTimeTV = findViewById(R.id.tv_total);//总时间


        //绑定服务
        intent = new Intent(this, AutoPlayService.class);//创建意图对象
        conn = new MusicPlayConn();//创建服务链接对象
        startService(intent);
        bindService(intent, conn, BIND_AUTO_CREATE);//绑定服务
    }

    static class MusicPlayConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            control = (AutoPlayService.MusicControl) iBinder;
            //初始化需要播放的音乐
            control.playMusic(songId);//开始 播放
            playStatus = PlayStatus.PLAYING;//正在播放
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

    @SuppressLint("HandlerLeak")
    public static Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            int duration = bundle.getInt("duration");                  //歌曲的总时长
            int currentPosition = bundle.getInt("currentPosition");//歌曲当前进度
            seekBar.setMax(duration);                //设置SeekBar的最大值为歌曲总时长
            seekBar.setProgress(currentPosition);//设置SeekBar当前的进度位置
            //刷新播放状态
            if (playStatus == PlayStatus.PAUSE) {
                playControlIB.setImageResource(R.drawable.play_start);
                if (animator.isRunning())//暂停
                    animator.pause();
            } else if (playStatus == PlayStatus.INIT) {//可能未初始化
                playStatus = PlayStatus.PLAYING;
            } else {
                playControlIB.setImageResource(R.drawable.play_pause);
                if (!animator.isRunning() || animator.isPaused())//开启
                    animator.start();
            }
            //歌曲的总时长
            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;
            //更新歌词显示
            if (lrc.size() != 0) {
                //存在歌词才需要刷新
                recyclerLrc(currentPosition);//通过当前进度刷新歌词显示
            }
            String strMinute;
            String strSecond;
            if (minute < 10) {              //如果歌曲的时间中的分钟小于10
                strMinute = "0" + minute; //在分钟的前面加一个0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {             //如果歌曲的时间中的秒钟小于10
                strSecond = "0" + second;//在秒钟前面加一个0
            } else {
                strSecond = second + "";
            }
            totalTimeTV.setText(strMinute + ":" + strSecond);
            //歌曲当前播放时长
            minute = currentPosition / 1000 / 60;
            second = currentPosition / 1000 % 60;
            if (minute < 10) {             //如果歌曲的时间中的分钟小于10
                strMinute = "0" + minute;//在分钟的前面加一个0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {               //如果歌曲的时间中的秒钟小于10
                strSecond = "0" + second;  //在秒钟前面加一个0
            } else {
                strSecond = second + "";
            }
            currentTimeTV.setText(strMinute + ":" + strSecond);
        }

        private void recyclerLrc(int currentPosition) {
            for (int i = 0; i < lrc.size(); i++) {//最大延迟0.2秒
                if (i < lrc.size() - 1) {//防止最后一句出问题
                    if ((currentPosition > lrc.get(i).first) && (currentPosition < lrc.get(i + 1).first)) {
                        int lastItem = currentItem;
                        currentItem = i + 1;//定位到下一行，提前显示
                        if (currentItem != lastItem) {//只有当变动时才需要修改
                            adapter.highLightItem(currentItem);
                            adapter.notifyItemChanged(currentItem);
                            centerLayoutManager.smoothScrollToPosition(recyclerViewLrc, new RecyclerView.State(), currentItem);
                        }
                        return;
                    }
                }
            }
        }
    };
    /**
     * 服务进行换歌时操作
     */
    @SuppressLint("HandlerLeak")
    public static Handler changeSongHandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            String id = bundle.getString("songId"); //歌曲的总时长
            if (id != null && !id.equals(songId)) {
                songId = id;//切换播放歌曲
                //需要切换歌词与歌曲封面
                new GetLrcTask().execute();
                new GetSongDetailTask().execute();
            }
        }
    };

    private void unbind(boolean isUnbind) {
        if (!isUnbind) {                  //判断服务是否被解绑
            unbindService(conn);      //解绑服务
        }
    }

    /**
     * 设置音量
     */
    private void setVolume() {
        //最大音量
        int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获取音乐的最大音量
        volumeAdjustment.setMax(streamMaxVolume);
        //当前音量
        int streamCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获取当前音量
        volumeAdjustment.setProgress(streamCurrentVolume);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        initClickEvent();//初始化控件的点击事件
        initSeekBarChangeEvent();//初始化进度条改变事件
        initRecyclerViewScrollEvent();//初始化recyclerView控件的滑动事件
    }

    /**
     * 初始化RecyclerView控件的滑动事件
     */
    private void initRecyclerViewScrollEvent() {
        //歌词滚动事件--用于实时显示选中项
        recyclerViewLrc.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstVisibleItemPosition = centerLayoutManager.findFirstVisibleItemPosition();//可见范围内的第一项的位置
                int lastVisibleItemPosition = centerLayoutManager.findLastVisibleItemPosition();//可见范围内的最后一项的位置
                currentItem = (lastVisibleItemPosition + firstVisibleItemPosition) / 2;//这里需要判断是否到底或者到顶了
                int i = Integer.parseInt(String.valueOf(lrc.get(currentItem).first));
                selectTime.setText(FormatTimeUtil.formatTimeToStr(i));
            }
        });
        //歌词滚动事件--用于实现显示与隐藏selectLinear
//        recyclerViewLrc.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                switch (newState) {
//                    case 0://停止滚动
//                        //定时器
//                        TimerTask timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(() -> {
//                                    selectLrcLinear.setVisibility(View.GONE);
//                                });
//                            }
//                        };
//                        //隐藏时间等
//                        new Timer().schedule(timerTask, 2000);
//                        break;
//                    case 1:
//                    case 2://正在拖动或者依赖惯性滚动
//                        selectLrcLinear.setVisibility(View.VISIBLE);
//                        break;
//                }
//            }
//        });
    }

    /**
     * 初始化进度条控件seekBar的事件
     */
    private void initSeekBarChangeEvent() {
        //声音大小调节
        volumeAdjustment.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);//调节系统音量
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //歌曲进度调节
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress == seekBar.getMax()) { //当滑动条滑到末端时，结束动画
                    animator.pause();                   //停止播放动画
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //设置seekbarThumb相对位置可大于进度条15，
                // 保证thumb在变成40dp直径后可以滑动到进度条最末尾
                seekBar.setThumbOffset(15);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setThumbOffset(0);
                //根据拖动的进度改变音乐播放进度
                int progress = seekBar.getProgress();//获取seekBar的进度
                control.seekTo(progress);         //改变播放进度
            }
        });
    }

    /**
     * 初始化控件的点击事件
     */
    private void initClickEvent() {
        /*封面切换*/
        showLrc.setOnClickListener(this);
        showLrcTwo.setOnClickListener(this);
        showImgAnimation.setOnClickListener(this);
        recyclerViewLrc.setOnClickListener(this);

        //点击切换进度事件
        selectLrcDuration.setOnClickListener(this);
        //声音关闭事件
        volumeControl.setOnClickListener(this);

        /*播放控制事件*/
        playTypeIB.setOnClickListener(this);//切换播放类型
        playLastIB.setOnClickListener(this);//播放上一首歌
        playControlIB.setOnClickListener(this);//播放开始\暂停\继续
        playNextIB.setOnClickListener(this);//播放下一首
        playListIB.setOnClickListener(this);//显示播放列表
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("HandlerLeak")
    Handler volumeHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == VOLUME_CHANGED) {
                setVolume();
            } else {
                throw new IllegalStateException("Unexpected value: " + msg.what);
            }
        }
    };

    /**
     * 各控件点击事件
     *
     * @param v 控件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_lrc:
            case R.id.show_lrc_two:
            case R.id.recycler_lrc:
                //显示封面页,隐藏歌单页
                showLrc.setVisibility(View.GONE);
                showImgAnimation.setVisibility(View.VISIBLE);
                break;
            case R.id.show_img_animation:
                //显示歌词页,隐藏封面页
                showLrc.setVisibility(View.VISIBLE);
                showImgAnimation.setVisibility(View.GONE);
                break;
            case R.id.volume_control:
                //点击关闭音乐声音
                int min = 0;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                    min = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);//最小音量
                }
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, min, 0);
                break;
            case R.id.play_type_image_button:
                //切换播放状态
                changePlayType();
                break;
            case R.id.play_last_image_button:
                //播放上一首歌
                playLastSong();
                break;
            case R.id.play_controller_image_button:
                //切换播放状态
                playControl();
                break;
            case R.id.play_next_image_button:
                //播放下一首歌
                playNextSong();
                break;
            case R.id.play_list_image_button:
                //打开播放列表信息
                openPlayList();
                break;
            default:
                break;

        }
    }

    /**
     * 展示播放列表信息
     */
    private void openPlayList() {
        viewPager.setVisibility(View.VISIBLE);
    }

    /**
     * 播放下一首歌
     * 按钮点击时的播放下一首均为播放列表的下一首歌
     */
    private void playNextSong() {
        control.playNextSong(playSongType);//播放下一首
    }

    /**
     * 播放状态控制
     */
    private void playControl() {
        switch (playStatus) {
            case INIT:
                control.play();           //播放音乐
                animator.start();
                playStatus = PlayStatus.PLAYING;
                playControlIB.setImageResource(R.drawable.play_pause);
                break;
            case PLAYING:               //暂停按钮点击事件
                control.pausePlay();     //暂停播放音乐
                animator.pause();
                playStatus = PlayStatus.PAUSE;
                playControlIB.setImageResource(R.drawable.play_start);
                break;
            case PAUSE:     //继续播放按钮点击事件
                control.continuePlay(); //继续播放音乐
                animator.start();
                playStatus = PlayStatus.PLAYING;
                playControlIB.setImageResource(R.drawable.play_pause);
                break;
        }
    }

    public enum PlayStatus {
        INIT,//初始化，暂未开始播放
        PAUSE,//暂停中
        PLAYING//播放中
    }

    /**
     * 隐藏viewPager
     */
    public void closePage(View view) {
        viewPager.setVisibility(View.GONE);
    }

    /**
     * 播放上一首歌
     */
    private void playLastSong() {
        control.playLastSong(playSongType);//根据当前状态播放上一首歌
    }

    /**
     * 切换播放类型
     */
    private void changePlayType() {
        switch (playSongType) {
            case SHUFFLE://随机播放->单曲循环
                playSongType = PlaySongType.SINGLES;
                playTypeIB.setImageResource(R.drawable.play_type_one);
                Toast.makeText(getContext(), "单曲循环", Toast.LENGTH_SHORT).show();
                break;
            case SINGLES://单曲循环->顺序循环
                playSongType = PlaySongType.SEQUENTIAL;
                playTypeIB.setImageResource(R.drawable.play_type_recycler);
                Toast.makeText(getContext(), "顺序播放", Toast.LENGTH_SHORT).show();
                break;
            case SEQUENTIAL://顺序循环->随机播放
                playSongType = PlaySongType.SHUFFLE;
                playTypeIB.setImageResource(R.drawable.play_type_random);
                Toast.makeText(getContext(), "随机播放", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    /**
     * 音量监控线程
     */
    class VolumeThread implements Runnable {
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                Message message = new Message();
                message.what = VOLUME_CHANGED;
                PlaySongActivity.this.volumeHandler.sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    /**
     * 获取歌词任务
     */
    static class GetLrcTask extends AsyncTask<Void, Void, List<Pair<Long, String>>> {

        @Override
        protected List<Pair<Long, String>> doInBackground(Void... voids) {
            String lrcBySongId = LrcDeal.getLrcBySongId(songId);
            return LrcDeal.parseLrcString(lrcBySongId);
        }

        @Override
        protected void onPostExecute(List<Pair<Long, String>> maps) {
            super.onPostExecute(maps);
            lrc.clear();
            lrc.addAll(maps);
            if (lrc.size() == 0) {
                //为解析出歌词时,不显示..页面
                showLrcTwo.setVisibility(View.GONE);
                noLrc.setVisibility(View.VISIBLE);
            } else {
                //解析出歌词时,恢复正常显示并刷新数据
                showLrcTwo.setVisibility(View.VISIBLE);
                noLrc.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 获取歌曲详情
     */
    static class GetSongDetailTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            currentSong = MusicDeal.getSongInfoById(songId);//歌曲信息
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //加载背景模糊图片
            Glide.with(getContext()).asBitmap().load(currentSong.getPicUrl()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    Bitmap bitmap = BlurUtil.doBlur(resource, 10, 10);
                    Palette palette = Palette.from(bitmap).generate();
                    Palette.Swatch swatch = palette.getVibrantSwatch();
                    if (swatch == null) {//无鲜明色调--颜色过于单调,则防止亮度过高,使用默认图片
                        swatch = palette.getDominantSwatch();//主色调
                        if (swatch != null && !(swatch.getHsl()[2] > 0.85)) {//正常亮度
                            bcgImg.setBackground(new BitmapDrawable(bitmap));
                        } else {//纯色背景修改
                            bcgImg.setBackgroundResource(R.drawable.bcg_account_fragment);
                        }
                    } else {
                        bcgImg.setBackground(new BitmapDrawable(bitmap));
                    }
                }
            });
            //加载封面合并图片
            Glide.with(getContext()).asBitmap().load(currentSong.getPicUrl()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    Bitmap mergeThumbnailBitmap = MergeImage.mergeThumbnailBitmap(albumBitmap, resource);
                    ivMusic.setImageBitmap(mergeThumbnailBitmap);//设置图片
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //记录服务是否解绑
        boolean isUnbind = false;
        unbind(isUnbind);//解绑服务
    }
}